package com.example.yimai.controller;

import com.example.yimai.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    /**
     * 获取图形验证码图片
     * @param response HTTP响应
     * @param key 验证码标识符
     */
    @GetMapping("/image")
    public void getCaptchaImage(HttpServletResponse response, @RequestParam String key) {
        try {
            captchaService.generateCaptchaImage(response, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证图形验证码
     * @param key 验证码标识符
     * @param captcha 用户输入的验证码
     * @return 验证结果
     */
    @PostMapping("/verify")
    public Map<String, Object> verifyCaptcha(@RequestParam String key, @RequestParam String captcha) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean isValid = captchaService.verifyCaptcha(key, captcha);
            if (isValid) {
                result.put("code", 200);
                result.put("message", "验证码正确");
            } else {
                result.put("code", 400);
                result.put("message", "验证码错误或已过期");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "验证失败: " + e.getMessage());
        }
        return result;
    }
}